package com.qfedu.common.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class DateConverter implements Converter<String, Date> {

	private final static Logger LOG = LogManager.getLogger(DateConverter.class);
	
	private static final List<String> formarts = new ArrayList<>(4);
	static {
		formarts.add("yyyy-MM");
		formarts.add("yyyy-MM-dd");
		formarts.add("yyyy-MM-dd hh:mm");
		formarts.add("yyyy-MM-dd hh:mm:ss");
	}

	@Override
	public Date convert(String source) {
		LOG.info("convert:" + source);
		String value = source.trim();
		if ("".equals(value)) {
			return null;
		}
		source = source.replace('T', ' ');
		if (source.matches("^\\d{4}-\\d{1,2}$")) {
			return DateUtil.parseDate(source, formarts.get(0));
		} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
			return DateUtil.parseDate(source, formarts.get(1));
		} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
			return DateUtil.parseDate(source, formarts.get(2));
		} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
			return DateUtil.parseDate(source, formarts.get(3));
		} else {
			throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
		}
	}
}
